package com.hzsd.zengbanyi.biaodan_text.Actrivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TextView;
import android.widget.Toast;

import com.hzsd.zengbanyi.biaodan_text.BaseActivity;
import com.hzsd.zengbanyi.biaodan_text.R;
import com.hzsd.zengbanyi.biaodan_text.bean.WorkDAO;
import com.hzsd.zengbanyi.biaodan_text.service.UploadLogService;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import hzst.android.util.FileUtil;
import hzst.android.util.MediaUtil;


public class Medio2Activity extends BaseActivity implements OnItemLongClickListener, OnClickListener, OnItemClickListener {
    private TextView tvChoose,tvSave,tv_cut;
    private String url;
	private RelativeLayout rlReturn;
	private String VIDEO_UNSPECIFIED = "video/*";
	private String absolutePath;
	private String filename,taskSceneId;
	private ProgressDialog selectorDialog;
	private UploadLogService logService;
	private File uploadFile;
	private boolean start = true;	
	private WorkDAO workdao;
	private ArrayList<HashMap<String, Object>> list;
	private ArrayList<String> mvList;
	private GridView gridView;
	private SimpleAdapter adapter;
	private String videopath = Environment.getExternalStorageDirectory().toString() + "/hjjc/videos/";

    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_medio2);
		rlReturn=(RelativeLayout)findViewById(R.id.rl_return);
		tvSave = (TextView)findViewById(R.id.tv_save);  
		gridView=(GridView)findViewById(R.id.gridview);
        tvChoose = (TextView)findViewById(R.id.tv_choose_pic);  
        tv_cut=(TextView) findViewById(R.id.tv_cut);
        
        
    	selectorDialog = new ProgressDialog(this);  
		selectorDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条的形式为圆形转动的进度条  
		selectorDialog.setCancelable(true);// 设置是否可以通过点击Back键取消  
		selectorDialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条  
		selectorDialog.setMessage("正在上传，请稍后..."); 
		SharedPreferences share = getSharedPreferences("user", MODE_PRIVATE);   
		taskSceneId=share.getString("taskSceneId","");
		list=new ArrayList<HashMap<String,Object>>();
		workdao=new WorkDAO(this);
		getList();
		gridView.setOnItemClickListener(this);
		gridView.setOnItemLongClickListener(this);
		rlReturn.setOnClickListener(this);
		tvSave.setOnClickListener(this);
		tvChoose.setOnClickListener(this);
		tv_cut.setOnClickListener(this);
        
    }  
    /**
     * 获取视频缩略图
     * @param filePath 地址
     * @return
     */
    public Bitmap getVideoThumbnail(String filePath) {  
        Bitmap bitmap = null;  
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();  
        try {  
            retriever.setDataSource(filePath);  
            bitmap = retriever.getFrameAtTime();  
        }   
        catch(IllegalArgumentException e) {  
            e.printStackTrace();  
        }   
        catch (RuntimeException e) {  
            e.printStackTrace();  
        }   
        finally {  
            try {  
                retriever.release();  
            }   
            catch (RuntimeException e) {  
                e.printStackTrace();  
            }  
        }  
        return bitmap;  
    }  
    
    /** 根据返回选择的文件，来进行上传操作 **/
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case 0:
			
			break;
		case 1:
			if (resultCode == Activity.RESULT_OK) {
				Uri uri = data.getData();
				
				try {
					url = MediaUtil.getPath(Medio2Activity.this, uri);
					String sceneId=workdao.GetMvSceneId(url);
					if(new File(url).length() > FileUtil.UNIT_MB*20){
						showMemberToast(Toast.LENGTH_SHORT, "上传文件大小不能超过20MB");
					}else{
						if (!(sceneId.equals(taskSceneId))) {
							workdao.addMediaPath(url, taskSceneId, 2);
							mvList=workdao.GetMvPath(taskSceneId);
							if(mvList.size()!=0) {
								Bitmap bit=getVideoThumbnail(url);
								String fileName = url.substring(url.lastIndexOf("/") + 1);
								HashMap<String,Object> map = new HashMap<String, Object>();
								map.put("path", fileName);
								map.put("pic", bit);
								list.add(map);
								if(adapter == null){
									
								}
								adapter.notifyDataSetChanged();
							}else{
								getList();
							}
						}else{
							Toast.makeText(Medio2Activity.this, "列表内已经有相同的视频", Toast.LENGTH_SHORT).show();
						}
					}
					} catch (Exception e) {
					e.printStackTrace();
				}
			}
			break;
		}
		
		
			
		super.onActivityResult(requestCode, resultCode, data);
	}
	/**
	 * 获取视频列表信息
	 */
	private void getList() {
		mvList=workdao.GetMvPath(taskSceneId);
		for (int i = 0; i < mvList.size(); i++) {
			Bitmap bit=getVideoThumbnail(mvList.get(i));
			Log.i("ht", "url" + mvList.get(i));
			String fileName = mvList.get(i).substring(mvList.get(i).lastIndexOf("/") + 1);
			HashMap<String,Object> map = new HashMap<String, Object>();
			map.put("path", fileName);
			map.put("pic", bit);
			list.add(map);
		}
		adapter = new SimpleAdapter(Medio2Activity.this,list,R.layout.simple_list_item,new String[]{"pic","path"},new int[]{R.id.iv,R.id.tv});
		adapter.setViewBinder(new ViewBinder() {
			@Override
			public boolean setViewValue(View view, Object object,
					String textRepresentation) {
				 //判断是否为我们要处理的对象  
	            if(view instanceof ImageView  && object instanceof Bitmap){  
	                ImageView iv = (ImageView) view;         
	                iv.setImageBitmap((Bitmap) object);  
	                return true;  
	            }else  
	            return false;  
			}
		});
		gridView.setAdapter(adapter);	
	}
	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		deleteDialog(position);
		return true;
	} 
	private void deleteDialog(final int position){
		AlertDialog.Builder builder = new AlertDialog.Builder(Medio2Activity.this); 
        builder.setTitle("你确定删除吗");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	workdao.deleteMediaPath(mvList.get(position), taskSceneId);
            	mvList.remove(position);
            	list.remove(position);
            	adapter.notifyDataSetChanged();
    			Toast.makeText(Medio2Activity.this, "删除成功", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                             
            }
        });
        builder.create().show();
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rl_return:
			finish();
			break;

		case R.id.tv_save:
			finish();
			break;
		case R.id.tv_choose_pic:
			Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT);

        	innerIntent.setType(VIDEO_UNSPECIFIED);

        	Intent wrapperIntent = Intent.createChooser(innerIntent, null);

        	startActivityForResult(wrapperIntent, 1);
			break;
		case R.id.tv_cut://录制视频
			Intent intent=new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
			String fileName=System.currentTimeMillis()+".mp4";
			File f=new File(videopath);
			if(!f.exists()){
				f.mkdirs();
			}
			f=new File(videopath, fileName);
			videopath=videopath+fileName;
			Uri uri=Uri.fromFile(f);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            startActivityForResult(intent, 0);
			break;
		}
	}
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		FileUtil fileUtil = new FileUtil(this);
		fileUtil.openFile(new File(mvList.get(position)));
	}
     
}

